/**
 *
 * @param file 上传组件,或者api返回的file对象
 * @param saveFilePathName 文件夹名称
 * @returns {Promise<unknown>}
 */

import {
	getStsToken,
	oss_getDefaultConfig
} from '@/common/bytAdmin/bytAdmin'

export function uploadOss(file, saveFilePathName = undefined) {
	return new Promise((resolve, reject) => {
		getStsToken().then((tokenRes) => {
				try {
					tokenRes = tokenRes.data
					if (uni.$u.test.isEmpty(file.url)) {
						file["url"] = file.path;
					}
					let fileName;
					//#ifdef APP-PLUS
					fileName = file.url.substring(file.url.indexOf("tmp/") + 4);
					//#endif
					//#ifndef APP-PLUS
					fileName = file.url.substring(file.url.lastIndexOf("/") + 1);
					//#endif
					console.log("fileName", fileName);
					// 租户iD
					let tenantId = uni.getStorageSync("tenantId");

					oss_getDefaultConfig({
						tenantId
					}).then(res => {
						const uploadUrl = res.data.endpoint
						const url = res.data.domain.includes('http') ? res.data.domain : 'http://' +
							res
							.data.domain

						uni.$u.http
							.upload(uploadUrl, {
								filePath: file.url,
								name: "file",
								formData: {
									key: `${
					    (tenantId ? tenantId + "/" : "") +
					    (saveFilePathName ? saveFilePathName : file.type) +
					    "/" +
					    fileName
					  }`,
									policy: tokenRes.encodedPolicy,
									"x-oss-security-token": tokenRes.securityToken,
									OSSAccessKeyId: tokenRes.aliyunAccessKeyId,
									signature: tokenRes.signature,
								},
							})
							.then((res) => {
								let address = `/${
					  (tenantId ? tenantId + "/" : "") +
					  (saveFilePathName ? saveFilePathName : file.type) +
					  "/" +
					  fileName
					}`;

								resolve({
									url: url + address
								});
							})
							.catch((err) => {
								console.log("上传失败:", err);
								uni.$u.toast("上传失败")
								reject();
							});
					}).catch((err) => {
						console.log("上传失败:", err);
						uni.$u.toast("上传失败")
						reject();
					});

				} catch (err) {
					console.log("上传失败:", err);
					uni.$u.toast("上传失败")
				}
			})
			.catch((err) => {
				console.log("上传失败:", err);
				uni.$u.toast("上传失败")
				reject(err);
			});

	});
}